package com.zatech.cgnci.project.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zatech.cgnci.project.base.context.UserContext;
import com.zatech.cgnci.project.base.enums.ApprovalConfigEnum;
import com.zatech.cgnci.project.base.enums.BusinessScenariosEnum;
import com.zatech.cgnci.project.base.enums.OperationTypeEnum;
import com.zatech.cgnci.project.base.utils.BeanUtils;
import com.zatech.cgnci.project.base.utils.VerifyUtils;
import com.zatech.cgnci.project.dto.*;
import com.zatech.cgnci.project.entity.CgnciAnnualInsurePlanDO;
import com.zatech.cgnci.project.entity.UserEntity;
import com.zatech.cgnci.project.service.CgnciAnnualInsurePlanService;
import com.zatech.cgnci.project.service.CgnciOperationLogsService;
import com.zatech.cgnci.project.service.IApprovalService;
import com.zatech.cgnci.project.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * <p>
 * 方案信息主表 前端控制器
 * </p>
 *
 * @author Generator
 * @since 2024-12-17
 */
@RestController
@RequestMapping("/api/insure-plan")
@RequiredArgsConstructor
@Api(produces = "application/json", tags = "年度最大净自留限额api接口文档")
public class CgnciAnnualInsurePlanController {

    private final CgnciAnnualInsurePlanService annualInsurePlanService;

    private final IApprovalService approvalService;

    private final CgnciOperationLogsService cgnciOperationLogsService;

    @PostMapping("/page")
    @ApiOperation(value = "分页列表查询")
    public IPage<CgnciAnnualInsurePlanPageVO> page(@RequestBody CgnciAnnualInsurePlanQueryDTO cgnciAnnualInsurePlanQueryDTO) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        IPage<CgnciAnnualInsurePlanPageVO> page = annualInsurePlanService.pageInsurePlan(cgnciAnnualInsurePlanQueryDTO);
        List<CgnciAnnualInsurePlanPageVO> records = page.getRecords();
        if (VerifyUtils.isNotEmpty(records)) {
            records.forEach(record -> record.setHasEdit("3".equals(record.getStatus()) && user.getNameAndCode().equals(record.getCreateUser())));
        }
        return page;
    }

    @GetMapping("/detail")
    @ApiOperation(value = "详情")
    public CgnciAnnualInsurePlanMainVO detail(@RequestParam(value = "inPlanId") @NotNull(message = "inPlanId不能为空") Long inPlanId) {
        return annualInsurePlanService.detail(inPlanId);
    }

    @PostMapping("/next/create")
    @ApiOperation(value = "新建险种最大净自留限额")
    @Transactional(rollbackFor = Exception.class)
    public Long nextCreate() {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        // 第一步先插入业务数据,用来绑定工作量formId formNo,并且关联工作台的跳转地址url以及参数
        CgnciAnnualInsurePlanDO annualInsurePlanDO = CgnciAnnualInsurePlanDO.builder()
                .formNo(BeanUtils.getUUID())
                .inPlanNo("R" + System.currentTimeMillis())
                .createUser(user.getNameAndCode())
                .updateUser(user.getNameAndCode()).build();
        annualInsurePlanService.save(annualInsurePlanDO);

        // 创建任务,绑定工作流formId. 并且关联工作台的跳转地址url以及参数
        ApprovalInfoVO approvalInfoVO = approvalService.create(FlowTaskCreateDTO.builder().approvalConfigGroupId(ApprovalConfigEnum.APPROVAL_CONFIG_001.getGroupId()).formId(String.valueOf(annualInsurePlanDO.getInPlanId())).formNo(annualInsurePlanDO.getFormNo())
                .redirectionUrl(ApprovalConfigEnum.APPROVAL_CONFIG_001.getRedirectionUrl()).redirectionParam(String.valueOf(annualInsurePlanDO.getInPlanId())).redirectionDesc(ApprovalConfigEnum.APPROVAL_CONFIG_001.getRedirectionDesc()).build());
        cgnciOperationLogsService.insertOperationLogs(
                String.valueOf(annualInsurePlanDO.getInPlanId()),
                BusinessScenariosEnum.INSURANCE.getCode(),
                OperationTypeEnum.ADD_INSURANCE_LIMIT.getCode(),
                "新增险种最大净自留限额任务号：" + approvalInfoVO.getTaskId(),
                user.getNameAndCode()
        );
        return annualInsurePlanDO.getInPlanId();
    }

    @PostMapping("/saveOrUpdate")
    @ApiOperation(value = "新增或者修改")
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(@RequestBody @Valid CgnciAnnualInsurePlanSaveOrUpdateDTO saveOrUpdateDTO) {
        CgnciAnnualInsurePlanDO annualInsurePlanDO = annualInsurePlanService.saveOrUpdateAnnualInsurePlan(saveOrUpdateDTO);

        // 提交审核
        if (VerifyUtils.isNotEmpty(saveOrUpdateDTO.getFlowTaskType()) && "submit".equals(saveOrUpdateDTO.getFlowTaskType())) {
            annualInsurePlanService.submit(FlowTaskSubmitDTO.builder().approvalInfoId(saveOrUpdateDTO.getApprovalInfoId()).formId(String.valueOf(annualInsurePlanDO.getInPlanId())).build());
        }
    }

    @GetMapping("/next/edit")
    @ApiOperation(value = "编辑险种最大净自留限额")
    @Transactional(rollbackFor = Exception.class)
    public Long nextEdit(@RequestParam(value = "inPlanId") @NotNull(message = "inPlanId不能为空") Long inPlanId) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        CgnciAnnualInsurePlanDO annualInsurePlanDO = annualInsurePlanService.nextEdit(inPlanId);

        // 创建任务,绑定工作流formId,formNo 并且关联工作台的跳转地址url以及参数
        ApprovalInfoVO approvalInfoVO = approvalService.create(FlowTaskCreateDTO.builder().approvalConfigGroupId(ApprovalConfigEnum.APPROVAL_CONFIG_002.getGroupId()).formId(String.valueOf(annualInsurePlanDO.getInPlanId())).formNo(annualInsurePlanDO.getFormNo())
                .redirectionUrl(ApprovalConfigEnum.APPROVAL_CONFIG_002.getRedirectionUrl()).redirectionParam(String.valueOf(annualInsurePlanDO.getInPlanId())).redirectionDesc(ApprovalConfigEnum.APPROVAL_CONFIG_002.getRedirectionDesc()).build());
        cgnciOperationLogsService.insertOperationLogs(
                String.valueOf(annualInsurePlanDO.getInPlanId()),
                BusinessScenariosEnum.INSURANCE.getCode(),
                OperationTypeEnum.EDIT_INSURANCE_LIMIT.getCode(),
                "编辑险种最大净自留限额任务号：" + approvalInfoVO.getTaskId(),
                user.getNameAndCode()
        );
        return annualInsurePlanDO.getInPlanId();
    }

    @PostMapping("/approve")
    @ApiOperation(value = "审核流程任务")
    public void approve(@RequestBody @Valid FlowTaskApprovalDTO flowTaskDTO) {
        annualInsurePlanService.approve(flowTaskDTO);
    }

    @GetMapping("/listBackNode")
    @ApiOperation(value = "获取退回流程节点")
    public List<ApprovalConfigVO> listBackNode(@RequestParam(value = "inPlanId") @NotNull(message = "inPlanId不能为空") Long inPlanId) {
        CgnciAnnualInsurePlanDO annualInsurePlan = annualInsurePlanService.getById(inPlanId);
        return approvalService.listBackNode(String.valueOf(annualInsurePlan.getInPlanId()), annualInsurePlan.getFormNo());
    }

    @PostMapping("/back")
    @ApiOperation(value = "退回流程任务")
    public void back(@RequestBody @Valid FlowTaskBackDTO flowTaskDTO) {
        annualInsurePlanService.back(flowTaskDTO);
    }

    @GetMapping("/signOut")
    @ApiOperation(value = "注销")
    public void signOut(@RequestParam(value = "inPlanId") @NotNull(message = "inPlanId不能为空") Long inPlanId) {
        annualInsurePlanService.signOut(inPlanId);
    }

    @GetMapping("/log")
    @ApiOperation(value = "获取操作日志")
    public List<ApprovalRecordVO> log(@RequestParam(value = "inPlanId") @NotNull(message = "inPlanId不能为空") Long inPlanId) {
        return annualInsurePlanService.log(inPlanId);
    }

    @GetMapping("/listPlanPolicy")
    @ApiOperation(value = "获取年度承保政策")
    public List<CgnciAnnualInsurePlanPolicyVO> listPlanPolicy(@RequestParam(value = "annual") @NotNull(message = "annual不能为空") String annual,
                                                              @RequestParam(value = "riskSubTypeCodes") @NotNull(message = "riskSubTypeCodes不能为空") String riskSubTypeCodes) {
        return annualInsurePlanService.listPlanPolicy(annual, riskSubTypeCodes);
    }

}

